var app = getApp()
//常量数据配置
var ConstantData = require('../../../common/constant_data.js')
var common = require("../../../common/common.js")
var BLELocker = require('../../../common/BLELocker.js')
var util = require('../../../utils/util.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showMaintPlatform: false,
    showUseOtherMini: false,
    platformTipDesc: '',
    noBackTipShow: false,
    noBackTipTxt: '',
    noLoginFlg: false,
    payStatus: true,
    pageNum: 1,
    numPerPage: 10,
    pageName:'user_deposit',
    alertBoxStatus: false,
    callServiceBoxStatus: false,
    msg: '去支付押金',
    loading_show: false,
    supplementPhone: 0, //补全手机号0不跳转到登录，1跳转到登录页面
    refundDepositTipInfo: '是否要申请退押金？', //退押金提示说明
    msgType: 0, //消息类型1未归还，2未支付租金
    alertBoxBtnName: '确  定', //消息提示框按钮名称
    isSubOffical: true,
    isShowMpDialog: false, //显示关注公众号对话框
    nowDepositPrice: 0, //当前申请退押金金额
    tempRefundData: null, //临时退款数据
    subMpBtnName:"关注公众号，查看进度",
    depositList: []
  },

  /**
   * 跳转到关注公众号的页面
   */
  goFollowMp: function() {
    this.setData({
      isShowMpDialog: false,
    });
    app.goFollowMp(-200003, '关注公众号-押金明细')
  },

  doNothing() {
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      isSubOffical: app.globalData.isSubOffical
    })
    // 记录展示关注公众号日志
    if (!app.globalData.isSubOffical) {
      app.recordShowMpLog(-200003, '关注公众号-押金明细')
    }

    this.getNetwork()
    let windowHeight = wx.getStorageSync('systeminfo').windowHeight
    this.setData({
      windowHeight: windowHeight
    })
    if (options.pt && options.orderCode && options.pt == "refund_ad") {
      this.setData({
        orderCode: options.orderCode
      })
      this.toRebundDeposit()
    } else {
      this.getApageDepositInfo();
      if (options.refundtip == 1) {
        wx.showToast({
          title: '申请成功',
        });
      }
    }   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.data.msgType = 0
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    let that = this
    that.data.msgType = 0
    clearInterval(that.data.timer)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    let that = this
    clearInterval(that.data.timer)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    console.log('onPullDownRefresh');
    let that = this;
    that.setData({
      depositList:[],
      pageNum: 1, //每次触发上拉事件，把searchPageNum+1  
    });
    that.getApageDepositInfo();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    
    var that = this;
    if (that.data.pageNum *that.data.numPerPage < that.data.total) {
      that.setData({
        pageNum: that.data.pageNum + 1, //每次触发上拉事件，把searchPageNum+1  
      });
      console.log(5555)
      that.getApageDepositInfo();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  //关闭未归还提示
  closeNoBackTip(){
     this.setData({
       noBackTipShow: false
     })
  },
  getNewList: function(){
    var that = this;
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_dposit/wxmini/record_list',
        method: 'post',
        header: header,
        data: {
          pageNum: 1,
          numPerPage: 10
        },
        success: function (res) {   
          if (res.data.result == 0 && that.data.depositList && res.data.data.data[0] && that.data.depositList[0] && res.data.data.data[0].stat != that.data.depositList[0].stat) {
            var oldList = that.data.depositList.slice(10)
            var newList = res.data.data.data.concat(oldList)
            newList.forEach(item=>{
              if(item.deposit){
                item.deposit=item.deposit.toString().split('.')
             }
            })
            that.setData({
              loadingComplete: true,
              depositList: newList
            })
            clearInterval(that.data.timer)
          } 
          if(res.data.subMpBtnName) {
            that.setData({
              subMpBtnName: res.data.subMpBtnName
            })
          }

          that.data.isSubOffical = !res.data.isTipSubOffical;
        },
        fail: function(){
          clearInterval(that.data.timer)
        }
      })

    })
  },
  getApageDepositInfo: function() {
    if(app.globalData.loginData && app.globalData.loginData.nophone == 1) {
      //需要重新登录      
      this.setData({
        noLoginFlg: true
      })
      return
    }
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    var that = this;
    app.executeRequest(function(header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_dposit/wxmini/record_list',
        method: 'post',
        header: header,
        data: {
          pageNum: that.data.pageNum,
          numPerPage: that.data.numPerPage
        },
        success: function(res) {
          that.setData({
            networkType:''
          })
          console.log("获取押金明细访问成功", res)
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          if (res.data.result == 0) {
            that.data.isSubOffical = !res.data.isTipSubOffical;
            if(res.data.subMpBtnName) {
              that.setData({
                subMpBtnName: res.data.subMpBtnName
              })
            }
            if (that.data.pageNum == 1) {
                //判断是否存在未归还的设备
            if(res.data.noBackStat === true) {
                that.setData({
                    noBackTipShow: true,
                    noBackTipTxt: res.data.noBackTipDesc
                })
            }
            }
  
            if (res.data.noDepositOrder) {
              that.setData({
                noDepositOrder: res.data.noDepositOrder
              })
            }
            if (res.data.lastOrderInfo) {
              that.setData({
                lastOrderInfo: res.data.lastOrderInfo
              })
            }
            // if (that.data.pageNum == 1) {
            //   let newList = res.data.data.data || [];
            //   newList.forEach(item=>{
            //     if(item.deposit){
            //       item.deposit=item.deposit.toString().split('.')
            //    }
            //   })
            //   that.setData({
            //     loading: false,
            //     loadingComplete: true,
            //     depositList: newList,
            //     total:res.data.data.total
            //   });
            //   return;
            // }
            var oldList = that.data.depositList || []
            var newList = oldList.concat(res.data.data.data)
            newList.forEach(item=>{
             if (typeof item.deposit == 'number') {
              item.deposit = item.deposit.toString().split('.')
            }
            })
            if (res.data.data.pageNum * res.data.data.numPerPage < res.data.data.total) {
              that.setData({
                loading: false,
                loadingComplete: true,
                depositList: newList,
                total:res.data.data.total
              });
            } else {
              that.setData({
                loading: true,
                loadingComplete: false,
                depositList:newList
              });
            }
        
          } else {
            wx.showToast({
              title: '获取失败'
            })
          }
        },
        complete(){
          getApp().hideLoading()
        }
      })

    })

  },
  /**
   * 监听网络状态
   */
  getNetwork: function () {
    var that = this;
    wx.getNetworkType({
      success: function (res) {
        // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        let networkType = res.networkType
        that.setData({
          networkType: networkType
        })
      }
    })
    if (wx.onNetworkStatusChange){
      wx.onNetworkStatusChange(function (res) {
        console.log(res)
        let networkType = res.networkType
        let isConnected = res.isConnected
        that.setData({
          networkType: networkType,
          isConnected: isConnected
        })
        if (isConnected) {
          that.getApageDepositInfo()
        }
      })
    } 
  },
  //支付押金
  toPayDeposit: function(event) {
    var that = this
    this.setData({
      // alertBoxStatus:true,
      eqtId: event.target.dataset.eqTid,
      orderCode: event.target.dataset.orderCode,
      msg: event.target.dataset.msg
    })
    wx.showModal({
      title: '温馨提示',
      content: '去支付',
      success: function() {
        that.toPay(this.data.orderCode)
      }
    })
  },
  toNoBackTip: function(e) {
    console.log('e--->', e)
    let equId = e.currentTarget.dataset.equId
    let hospitalName = e.currentTarget.dataset.hospitalName
    let positions = e.currentTarget.dataset.positions
    let orderCode=e.currentTarget.dataset.orderCode
    let equType = e.currentTarget.dataset.type
    wx.navigateTo({
      url: '/pages/index/no_back_tip/no_back_tip?equId=' + equId + "&hospitalName=" + hospitalName + '&positions=' + positions + '&equType=' + equType + '&orderCode=' + orderCode,
    })
  },
  // 扫码还
  // scanToStill:function(){
  //   wx.switchTab({
  //     url: '/pages/index/index'
  //   })
  // },
    /**
   * 扫码归还
   */
  scanToStill: function () {
    console.log("scanBack");
    let pages = getCurrentPages()
    let currPage = null //当前页面
    let prevPage = null //上一个页面
    currPage = pages[pages.length - 1] //当前页面
    prevPage = pages[pages.length - 2] //上一个页面
    if (prevPage && prevPage.data.pageName == 'user_deposit') {
      wx.reLaunch({
        url: '/pages/index/index?pt=noback&depositAutoBack=true',
      })
      return
    }
    wx.reLaunch({
      url: '/pages/index/index?pt=noback',
    })
  },
  payAction: function() {
    app.toPay(this.data.orderCode)
  },
  //支付租金
  toPayLease: function(event) {
    var extdata = event.currentTarget.dataset.extdata;
    var wxnodeposit = event.currentTarget.dataset.wxnodeposit;
    console.log("------>111>extdata=", extdata, wxnodeposit);
    if (extdata && wxnodeposit != 'REVOKED') {
      wx.navigateToMiniProgram({
        appId: 'wxd8f3793ea3b935b8',
        path: "pages/record/detail",
        extraData: extdata
      })
      return;
    }
    var orderCode = event.currentTarget.dataset.ordercode
    this.toPay(orderCode,true)
  },
  
  toPayOrder: function(orderCode) {
    var that = this
    console.log("去微信支付。。。" + orderCode)
    app.toPayValideLogin(orderCode, function(loginCode, orderCode, err){

      app.executeRequest(function(header) {

        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/weixin/pay',
          method: 'post',
          header: header,
          data: {
            orderCode: orderCode,
            loginCode: loginCode,
            wxErr: err
          },
          success: function(res) {
            var data = res.data
            console.log("支付结果---" + data.result)
            if (data.result != 0 || !data.data || !data.data.timeStamp) {
              console.log("租金支付失败----result=" + data.result + ",description=" + data.description)
              that.setData({
                msg: data.description ? data.description:'支付失败',
                alertBoxStatus: true
              })
              return
            }
            wx.requestPayment({
              appId: 'wx0e458dc331e557cc',
              timeStamp: data.data.timeStamp,
              nonceStr: data.data.nonceStr,
              package: data.data.package,
              signType: data.data.signType,
              paySign: data.data.paySign,
              success: function(res) {
                console.log("SUCCESS")
                console.log(res);
                that.setData({
                  pageNum: 1, //每次触发上拉事件，把searchPageNum+1  
                  leseList: []
                });
        
                setTimeout(()=>{
                  that.getApageDepositInfo();
                },1500);
              },
              fail: function(res) {
                common.recordErrorInfo(ConstantData.err_type.pay_fail, res ? 'udep-' + JSON.stringify(res) : '');
              },
              complete: function(res) {
                console.log("complete--" + data.data.paySign)
                console.log(res)
              }
            })
          },
          complete: function(res) {
            console.log("恢复支付。。。")
            that.setData({
              payStatus: true
            })
          }
        })
  
      })

    }); 
    

  },
  /**
   * 确定消息提示弹框
   */
  sureTip: function() {
    this.setData({
      alertBoxStatus: false
    })
    var msgType = this.data.msgType

    console.log("---------->>msgType=" + msgType)

    if (msgType == 1) {
      //未归还，跳转到首页
      wx.reLaunch({
        url: '../../index/index?pt=noreturnequ',
      });
    } else if (msgType == 2) {
      //未支付租金，跳转到租金列表
      wx.redirectTo({
        url: '../../user_record/lease/user_lease',
      });
    } else if (msgType == 3) {
      wx.redirectTo({
        url: '../../index/index?pt=nophone',
      });
    }
  },

  retunHome() {
    wx.redirectTo({
      url: '../../index/index',
    });
  },
  
  //点击申请退押金
  refoundDeposit: function(event) {
    var that = this
    var eqTid = event.currentTarget.dataset.eqtid
    var orderCode = event.currentTarget.dataset.ordercode
    var equName = event.currentTarget.dataset.equname
    var deposit = event.currentTarget.dataset.deposit
    
    that.data.orderCode = orderCode;
    that.data.noSubMpRefundFlg = false;

    console.log("---------eqTid=", eqTid)
    console.log("---------orderCode=", orderCode)
    console.log("---------equName=", equName)
    console.log("---------deposit=", deposit)

    if (!that.data.isSubOffical) {
      //没有关注公众号，弹窗提示关注
      if (deposit == undefined || deposit == null) {
        deposit = 0;
      }
      that.setData({
        nowDepositPrice: parseFloat(deposit).toFixed(2)
      });
      // sanglongjia 去掉关注公众号，继续申请退押金
      // that.setData({
      //   isShowMpDialog: true,  
      //   tempRefundData: {
      //     eqTid: eqTid,
      //     orderCode: orderCode,
      //     equName: equName
      //   }
      // });
      // sanglongjia 去掉关注公众号，继续申请退押金
      that.confirmRefoundDeposit(eqTid, orderCode, equName)
    }else {
      //已经关注公众号，继续申请退押金
      that.confirmRefoundDeposit(eqTid, orderCode, equName)
    }
  },

  // 暂不关注公众号，申请退押金
  dontSubMpRefoundDeposit() {
    var that = this
    that.data.noSubMpRefundFlg = true;
    that.setData({
      isShowMpDialog: false
    });

    that.confirmRefoundDeposit(that.data.tempRefundData.eqTid, that.data.tempRefundData.orderCode, that.data.tempRefundData.equName)
  },

  //发起申请退押金请求
  confirmRefoundDeposit(eqTid, orderCode, equName) {
    var that = this
    
    wx.showLoading({
      title: '申请中...',
      mask: true
    });
    app.executeRequest(function(header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_time_card/left_time',
        method: 'post',
        header: header,
        data: {
          eqTid: eqTid
        },
        success: function(res) {
          getApp().hideLoading();
          console.log(res)
          var leftTime = res.data.data
          console.log("----------->leftTime=", leftTime)
          if (leftTime <= 0) {
            console.log("---------------不存在包时卡")
            if(that.data.noSubMpRefundFlg) {
               //直接退押金
               that.refundAdShow(); 
            }else {
                //不存在包时卡时长
                that.setData({
                  callServiceBoxStatus: true,
                  eqtId: eqTid,
                  orderCode: orderCode,
                  equName: equName,
                  refundDepositTipInfo: '请确认是否退押金？'
                })
            }
            
          } else {
            console.log("---------------存在包时卡")
            //存在包时卡时长
            that.setData({
              callServiceBoxStatus: true,
              eqtId: event.target.dataset.eqTid,
              orderCode: event.currentTarget.dataset.ordercode,
              equName: equName,
              refundDepositTipInfo: '退押金后包时卡剩余时间将被收回'
            })
          }
        }
      })

    })
  },

  cancleRebund: function() {
    this.setData({
      callServiceBoxStatus: false
    })
  },
  //退押金前的广告
  refundAdShow: function() {
    var that = this
    this.getAdInfo(that.data.orderCode)
  },
  //申请退押金
  toRebundDeposit: function() {
    wx.showLoading({
      title: '正在处理...',
      mask: true
    });
    this.setData({
      callServiceBoxStatus: false
    })
    var that = this
    console.log("申请退款----" + that.data.orderCode)

    app.executeRequest(function(header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_dposit/wxmini/refund_d',
        method: 'post',
        header: header,
        data: {
          orderCode: that.data.orderCode
        },
        success: function(res) {
          getApp().hideLoading();
          console.log(res)
          var data = res.data.result
          that.setData({
            supplementPhone: 0,
            alertBoxBtnName: "确  定",
          });
          if (data == 0) {
            that.data.depositList = []
            that.setData({
              loading: true,
              loadingComplete: false,
              pageNum: 1
            });
            if (res.data.description) {
              //银行卡退款提示
              that.setData({
                alertBoxStatus: true,
                msg: res.data.description,
                alertBoxBtnName: "确  定",
                msgType: 0
              });
            }
            that.data.timer = setInterval(()=>{
              that.getNewList()
              console.log('getNewList')
            },2000)
            that.getApageDepositInfo()
          } else if (data == 1) {
            var equNum = res.data.data
            var equName = that.data.equName
            that.setData({
              msg: '请确认' + equNum + '号' + equName + '已插入到归位桩,并扫描该轮椅所在桩位上的二维码完成信息更新后再申请退押金',
              msgType: 1,
              alertBoxStatus: true,
              alertBoxBtnName: "去扫码"
            })
          } else if (data == 2) {
            that.setData({
              msg: '有未支付的租金,请去支付',
              msgType: 2,
              alertBoxStatus: true
            })
          } else if (data == 3) {
            that.setData({
              msg: '参数有误，请查证',
              msgType: 0,
              alertBoxStatus: true
            })
          } else if (data == -132) {
            //退款超出频率限制
            var desc = res.data.description
            that.data.depositList = []
            that.setData({
              msg: desc,
              msgType: 0,
              alertBoxStatus: true,
              loading: true,
              loadingComplete: false,
              pageNum: 1
            })
            that.getApageDepositInfo()
          } else if (data == -101) { //需要登录
            that.setData({
              alertBoxStatus: true,
              msgType: 3,
              msg: "请使用手机号登录后,再申请",
              supplementPhone: 1
            })
          } else {
            that.setData({
              msg: 'error' + data,
              alertBoxStatus: true
            })
          }
        },
        fail: function(res) {
          getApp().hideLoading();
          console.log("申请退款访问失败")
          console.log(res)
        }
      })

    })

  },
  toPayDeposit: function(event) {
    this.toPay(event.currentTarget.dataset.ordercode)
  }, 
  toPay: function (orderCode, flg) {
    var that = this
    if (flg) {
      var depositAutoBack = true
    } else {
      var depositAutoBack = false
    }
    if (that.data.payStatus) { } else {
      console.log("支付中。。。。")
      return
    }
    that.setData({
      payStatus: false
    })
    console.log("去支付。。。" + orderCode, "/ejiam/wxmini/unpay/payment",depositAutoBack);

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/unpay/payment',
        method: 'post',
        header: header,
        data: {
          ordernum: orderCode,
          depositAutoBack: depositAutoBack
        },
        success: function (res) {
          var data = res.data
          console.log("支付结果---" + data.result)
          if (data.result == 0) {
            that.setData({
              alertBoxStatus: true,
              msg: data.description,
              pageNum: 1,
              leseList: []
            })
            setTimeout(() => {
              that.getApageDepositInfo();
            }, 1500);
            console.log("刷新支付记录")
          } else if (data.result == -1) {
            console.log("开始微信支付")
            that.toPayOrder(orderCode)
          } else {
            that.setData({
              alertBoxStatus: true,
              msg: data.description
            })
          }

        },
        complete: function (res) {
          console.log("恢复支付")
          that.setData({
            payStatus: true
          })
        }
      })

    })

  },

  /**
   * 获取广告内容
   */
  getAdInfo: function(orderCode) {
    var that = this
    wx.request({
      url: ConstantData.CONSTATNT_DATA.BASE_URL + '/leasead/mi_refund_deposit',
      method: 'post',
      data: {
        oc: orderCode
      },
      success: function(res) {
        var data = res.data
        try {
          if (data && Object.getOwnPropertyNames(data).length > 0) {
            wx.redirectTo({
              url: '../../pkgBak/pages/ad/hospital/wx_common_num?oc=' + orderCode + "&title=" + data.title + "&qrcodeImg=" + data.qrcodeSrc + "&desc=" + data.desc + "&qrcodeTitle=" + data.qrcodeTitle,
            })
          } else {
            that.toRebundDeposit()
          }
        } catch (err) {
          that.toRebundDeposit()
        }
      },
      fail: function(res) {
        that.toRebundDeposit()
      }
    })
  },
  closeDia:function(){
    this.setData({
      noBackTipShow:false
    })
  },
  copyText(e) {
    let key = e.currentTarget.dataset.key;
    util.copyContent(key)
  },
  /**
   * 返回首页
   */
  backHome: function() {
      wx.reLaunch({
        url: '/pages/index/index',
      })
  }

})